package com.adcok.lcdns.activity.ad;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.adcok.lcdns.util.ApplicationUtils;
import com.adcok.lcdns.util.LottoAdImageDownloaderFile;
import com.adcok.lcdns.util.LottoAdOverButton;
import com.adcok.lcdns.util.UnbindHelper;
import com.adcok.lcdns.R;

public class LottoAdReViewActivity extends Activity{

	private ImageView mAdImage;
//	private LinearLayout mPageLayout;
	
	/*
	 * mPageLayout의 show여부(true:보여짐, false: 숨김)
	 */
	private boolean mShowPageLayout;
	
	private LottoAdImageDownloaderFile mImageDownloader;
	private ProgressBar mProgressBar;
	
	private Context mContext;
	private ArrayList<String> mOriginArr;
	private ArrayList<String> mPhoneNumberArr;
	
	/** 이전 버튼 **/
	private Button mPrevBtn;
	/** 다음 버튼 **/
	private Button mNextBtn;
	/** 전화걸기 버튼 **/
	private Button mCallBtn;
	
	/** 광고 페이징 카운트 텍스트뷰 **/
	private TextView mCountTv;
	
	private Bundle mExtras;
	
	/*
	 * 이전에 선택되었던 페이지(이미지) 번호
	 */
	private int mPrevPage = -1;
	private int mPage = 0;
	private int mTotalPage = 0;;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.mContext = this;
		setContentView(R.layout.lottoad_review_ad);
		
		
		
		mExtras = getIntent().getExtras();
		
		/*####### Ben ########*/
		// 선택된 페이지를 바로 볼 수 있도록 이전 extra는 삭제하고 extras bundle에 담겨있는 정보 읽어 설정.
//		Intent intent = getIntent();
//		mOriginArr = intent.getStringArrayListExtra("originArr");
//		여기까지 이전 코드.. 추후 삭제.
//		여기부터 신규코드..
		mOriginArr = mExtras.getStringArrayList("originArr");
		mPhoneNumberArr = mExtras.getStringArrayList("adPhoneNumberArr");
		mPage = mExtras.getInt("selectedItem");
		
		
		
		if(mOriginArr != null){
			mTotalPage = mOriginArr.size();
		}
		
		mImageDownloader = new LottoAdImageDownloaderFile(mContext);
		mProgressBar = (ProgressBar) findViewById(R.id.pb_review_progress);
		mCountTv = (TextView) findViewById(R.id.tv_review_pagenumber);
		
//		mPageLayout = (LinearLayout) findViewById(R.id.ll_review_pagenumber_area);
//		mPageLayout.setVisibility(View.VISIBLE);
		mShowPageLayout = true;
		
		mPrevBtn = (Button) findViewById(R.id.btn_review_previous);
		mNextBtn = (Button) findViewById(R.id.btn_review_next);
		mCallBtn = (Button) findViewById(R.id.btn_review_right);
		
		mPrevBtn.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Drawable getBackground = v.getBackground();
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					v.setBackgroundDrawable(LottoAdOverButton.grayimg(getBackground));
				}
				else if(event.getAction() == MotionEvent.ACTION_UP){
					getBackground.clearColorFilter();
					v.setBackgroundDrawable(getBackground);
					if(mPage > 0){ // 페이지 숫자가 1보다 클경우 
						mPage--;
						updateUI();
					} else {
						ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), "첫번째 페이지 입니다.");
					}
				}
				return false;
			}
		});
		
		mNextBtn.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Drawable getBackground = v.getBackground();
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					v.setBackgroundDrawable(LottoAdOverButton.grayimg(getBackground));
				}
				else if(event.getAction() == MotionEvent.ACTION_UP){
					getBackground.clearColorFilter();
					v.setBackgroundDrawable(getBackground);
					if(mPage < mTotalPage - 1){ // 현재페이지보다 토탈페이지가 클 경우
						mPage++;
						updateUI();
					} else {
						ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), "마지막 페이지 입니다.");
					}
				}
				return false;
			}
		});
		
		
		mCallBtn.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Drawable getBackground = v.getBackground();
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					v.setBackgroundDrawable(LottoAdOverButton.grayimg(getBackground));
				}
				else if(event.getAction() == MotionEvent.ACTION_UP){
					getBackground.clearColorFilter();
					v.setBackgroundDrawable(getBackground);
					try {
						startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mPhoneNumberArr.get(mPage))));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				return false;
			}
		});
		
		mAdImage = (ImageView) findViewById(R.id.iv_review_adimage);
		/*####### Ben ########*/
		// 다시보기에서 화살표 숨김/나타냄 이벤트 제거.
//		mAdImage.setOnTouchListener(new View.OnTouchListener() {
//			
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				mShowPageLayout = !mShowPageLayout;
//				if(mShowPageLayout == true) {
//					mPageLayout.setVisibility(View.VISIBLE);
//				} else {
//					mPageLayout.setVisibility(View.GONE);
//				}
//				CNCronosLog.d("mAdImage touch event");
//				return false;
//			}
//		});
		
//		mPageLayout.setOnTouchListener(new View.OnTouchListener() {
//			
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				// TODO Auto-generated method stub
//				CNCronosLog.d("mPageLayout touch event");
//				return true;
//			}
//		});
		updateUI();
	}
	
	private void recycleBitmap(ImageView iv) {
		if(iv != null) {
			try {
				Drawable d = iv.getDrawable();
				if(d instanceof BitmapDrawable) {
					Bitmap b = ((BitmapDrawable)d).getBitmap();
					b.recycle();
				}
				
				d.setCallback(null);
			} catch(Exception e) {
				e.getStackTrace();
			}
		}
	}
	
	private void updateUI(){
		if(mPrevPage != -1) {
			recycleBitmap(mAdImage);
		}
		mImageDownloader.download(mOriginArr.get(mPage), mAdImage, mProgressBar);
		mCountTv.setText((mPage + 1) + " / " + mTotalPage);
		
		// 이미지 삭제를 위해 현재 페이지 번호 저장
		mPrevPage = mPage;
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if(mPrevPage != -1) {
			recycleBitmap(mAdImage);
		}
		super.onDestroy();
		UnbindHelper.unbindReferences(getWindow().getDecorView().getRootView()); // 사용한 뷰를 메모리에서 제거 한다.
		System.gc(); // 가비지컬렉션 수행
	}
}
